package com.vieewer.btdemo.view.wifi;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import static com.vieewer.btdemo.view.wifi.TransferPhotosManager.paths;
import static com.vieewer.btdemo.view.wifi.TransferPhotosManager.peerAddress;


/**
 * A simple server socket that accepts connection and writes some data on
 * the stream.
 */
public class FileServerAsyncTask extends
        AsyncTask<Void, Void, String> {

    private Context context;
    private File file;

    /**
     * @param context
     */
    public FileServerAsyncTask(Context context) {
        this.context = context;
    }
    @Override
    protected String doInBackground(Void... params) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        boolean flag = false;
        try {
            Log.i("tag", "file doinback");
            ServerSocket serverSocket = new ServerSocket(8888);
            //设置端口复用
            serverSocket.setReuseAddress(true);
            Socket client = serverSocket.accept();

//            peerAddress = client.getInetAddress().getHostAddress();//获取peer的ip

//            TransferPhotosActivity.peerAddress = client.getInetAddress().getHostAddress();//获取peer的ip
            Log.i("tag","FileTask peerIp:"+ peerAddress);


            String dirPath = Environment.getExternalStorageDirectory() +  "/" + "RecvPicture";
            /*final File f = new File(
                    Environment.getExternalStorageDirectory() +  "/" + "RecvPicture"+
                            "/wifip2pshared-" + System.currentTimeMillis() + ".jpg");
*/
//            File dirs = new File(f.getParent());
            File dirs = new File(dirPath);
            if (!dirs.exists())
                dirs.mkdirs();
            final File f = new File(dirPath +"/wifip2pshared-" + System.currentTimeMillis() + ".jpg");
            f.createNewFile();

            file = f;
            inputStream = client.getInputStream();
            outputStream = new FileOutputStream(f);
            flag = copyFile(inputStream, outputStream);
                outputStream.flush();//

            /**
             * 如果接收成功返回接收成功消息
             */
            if(flag){
                dataOutputStream = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));//
                dataOutputStream.writeUTF("Send Success!");
                dataOutputStream.flush();
            }

            client.close();
            serverSocket.close();
            return f.getAbsolutePath();

        } catch (IOException e) {
            Log.e("tag", e.toString());
            return null;
        }finally {
            try{
                if(inputStream != null){
                    inputStream.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
                if(dataOutputStream != null){
                    dataOutputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(String result) {
//Runs on the UI thread after doInBackground(Params...).
// The specified result is the value returned by doInBackground(Params...).
        Log.i("tag", "file onpost");
        if(result != null){
            Toast.makeText(context, "RecvPic:"+result, Toast.LENGTH_SHORT).show();
        }

        if (result != null) {
//            statusText.setText("RecvPic: " + result);
            //保存所有接收图片的路径
            paths.add(result);
            for(int i = 0 ;i<paths.size();i++){
                Log.i("tag","Path:"+paths.get(i)+"\n");
            }
            //Handler发送路径回主线程
            Message message = TransferPhotosManager.mHandler.obtainMessage();
//            Bundle bundle = new Bundle();
            message.what = 0X101;
            message.obj = paths;
//            bundle.putString("picturePath",result);
//            message.setData(bundle);
            TransferPhotosManager.mHandler.sendMessage(message);

//            Intent intent = new Intent();
//            intent.setAction(Intent.ACTION_VIEW);
//            intent.setDataAndType(Uri.parse("file://" + result), "image/*");
//            context.startActivity(intent);

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data;
            // 判断版本大于等于7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //通过FileProvider创建一个content类型的Uri,"com.fiberhome.xk.wifidirect.fileProvider"即是在清单文件中配置的authorities
                data = FileProvider.getUriForFile(context, "com.fiberhome.xk.wifidirect.fileProvider", file);
                // 给目标应用一个临时授权
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                data = Uri.fromFile(file);
            }
            intent.setDataAndType(data, "image/*");
            context.startActivity(intent);

        }

    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {

    }


    public static boolean copyFile(InputStream inputStream, OutputStream out) {
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
//            out.close();
//            inputStream.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }
}